package com.ingenio.siot.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.siot.Helper;
import com.ingenio.siot.adapter.CriterioAdapter;
import com.ingenio.siot.adapter.CriterioIntervaloAdapter;
import com.ingenio.siot.entity.Criterio;
import com.ingenio.siot.entity.Estado;

/**
 * Servlet implementation class DevolverAlturaServlet
 */
@WebServlet("/DevolverEstado")
public class DevolverEstadoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DevolverEstadoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			JSONObject json = new JSONObject();
			if(request.getParameter("id") != null && Helper.isInteger(request.getParameter("id").trim())){
				Integer id = Integer.parseInt(request.getParameter("id").trim());
				
				CriterioAdapter ca = new CriterioAdapter();
				Criterio c =ca.devolverCriterio(id);
				
				if(c != null){
					CriterioIntervaloAdapter cia = new CriterioIntervaloAdapter();
					List<Estado> estados = cia.devolverEstadosCriterio(c);
					
					JSONArray ja = new JSONArray();
					for (Estado estado : estados) {
					JSONObject row = new JSONObject();
					row.put("id", estado.getIdEstado());
					row.put("desc", estado.getDescEstado());
					ja.put(row);
				  }
				  json.put("estados", ja);
				}
				else {
				  json.put("error", "No recupera criterio");
				}
			}else {
				json.put("error", "error id");
			}
			response.setContentType("application/json");
			response.getWriter().write(json.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
